package com.iwuke.dance.util;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.google.android.material.textfield.TextInputEditText;

import androidx.annotation.NonNull;

/**
 * @author: 魏从响
 * @date: 2025/9/16
 */
public class TextInputEditTextUtil {

    private final Context context;
    private final TextInputEditText[] codeFields;
    private OnEditTextClick onEditTextClick;

    public TextInputEditTextUtil(Context context, TextInputEditText[] codeFields){
        this.context = context;

        this.codeFields = codeFields;
    }

    public void init(){
        // 设置输入监听
        setupCodeInputListeners();
        //自动聚焦首项
        // 在onCreate中添加
        codeFields[0].postDelayed(() -> {
            codeFields[0].requestFocus();
            showKeyboard(codeFields[0]);
        }, 300);
    }


    private void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager)
                context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }

    private Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    for (int i = 6; i <= codeFields.length; i--){
                        if ( i > 0) {
                            // 删除时返回前一位
                            codeFields[i - 1].requestFocus();
                            codeFields[i - 1].setText("");
                        }
                    }
                    break;
            }
        }
    };
    public void deleteData(){

        if (handler!=null){
            handler.sendEmptyMessageDelayed(1,100);
        }
    }

    public void removeCallbacks(){
        if (handler!=null){
            handler.removeCallbacks(null);
            handler=null;
        }
    }

    //智能输入跳转逻辑
    private void setupCodeInputListeners() {
        for (int i = 0; i < codeFields.length; i++) {
            final int currentIndex = i;

            codeFields[i].addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() == 1) {
                        // 自动跳转下一个
                        if (currentIndex < codeFields.length - 1) {
                            codeFields[currentIndex + 1].setFocusableInTouchMode(true);
                            codeFields[currentIndex].setFocusable(false);
                            codeFields[currentIndex + 1].requestFocus();
                        } else {
                            // 最后一位输入完成
                            submitVerificationCode();
                        }
                    } else if (s.length() == 0 && currentIndex > 0) {
                        codeFields[currentIndex - 1].setFocusableInTouchMode(true);
                        codeFields[currentIndex].setFocusable(false);
                        // 删除时返回前一位
                        codeFields[currentIndex - 1].requestFocus();
                    }
                }
            });

            // 处理键盘删除键
            codeFields[i].setOnKeyListener((v, keyCode, event) -> {
                if (keyCode == KeyEvent.KEYCODE_DEL &&
                        event.getAction() == KeyEvent.ACTION_DOWN &&
                        ((EditText)v).getText().length() == 0) {

                    if (currentIndex > 0) {
                        codeFields[currentIndex - 1].requestFocus();
                        codeFields[currentIndex - 1].setText("");
                    }
                    return true;
                }
                return false;
            });
        }
    }


    //获取完整验证码
    private String getEnteredCode() {
        StringBuilder code = new StringBuilder();
        for (TextInputEditText field : codeFields) {
            code.append(field.getText().toString());
        }
        return code.toString();
    }

    private void submitVerificationCode() {
        String fullCode = getEnteredCode();
        if (fullCode.length() == 6) {
            // 执行验证逻辑
//            verifyCodeOnServer(fullCode);
            LogUtil.logD("验证码",fullCode);
            Log.d("+++++++++",fullCode);
            Log.i("+++++++++",fullCode);
            Log.e("+++++++++",fullCode);

            if (onEditTextClick!=null){
                onEditTextClick.onEditTextClick(fullCode);
            }

        }

        // ...验证逻辑

        // 添加视觉反馈
        for (TextInputEditText field : codeFields) {
            field.animate()
                    .scaleX(0.9f).scaleY(0.9f)
                    .setDuration(100)
                    .withEndAction(() -> field.animate().scaleX(1).scaleY(1))
                    .start();
        }
    }

    public void setOnEditTextClick(OnEditTextClick onEditTextClick){

        this.onEditTextClick = onEditTextClick;
    }

    public interface OnEditTextClick{
        void onEditTextClick(String value);
    }
}
